#!/bin/bash
#
#	XBMC Language Filter
# 
#	Created by Brock Haymond 9/6/12.
#	Copyright (c) 2012 Brock Haymond <http://brockhaymond.com>.  All rights reserved.
#
# 	Bash script to call perl script "parse_srt.pl" recursively, capture running time, and output the logfile.
#

if [ "$#" -lt 1 ]
then
	echo ""
	echo "XBMC Language Filter by Brock Haymond (v1.0)"
	echo ""
	echo "Usage:"
	echo "    ./xbmclf [subtitle.srt] or [subtitles folder]" 
	echo ""
	echo "Press enter to close."
	read pause
	exit 1
fi

begin=`perl -MTime::HiRes -e 'print(1*Time::HiRes::gettimeofday),"\n"'`

export TERM=xterm-color

echo ""
echo "XBMC Language Filter by Brock Haymond (v1.0)"
echo ""
echo "Creating XBMC-compatible EDL file(s)"
echo "-------------------------------------"

NOW=$(date +"%r %m-%d-%Y")
echo "Logfile was generated by XBMC Language Filter at $NOW">~/"XBMC Language Filter.log"

INDEX=0
function RECURSE {
for FILE in "$@"
do
	if [ -d "$FILE" ]
	then 
		for F in "$FILE/"*
		do
			RECURSE "$F"

		done
	else 
		if [[ ${FILE: -4} == ".srt" ]]
		then
		  echo "Processing "$FILE"..." | tee -a ~/"XBMC Language Filter.log" 
		  NEW=$RESULT`perl parse_srt.pl "$FILE"`
		  if [ -z "$NEW" ]
		  then
		    INDEX=`expr $INDEX + 1`
		  else
		    RESULT="$NEW"
		  fi
		  
		fi
	fi
done  
}
RECURSE "$@"

end=`perl -MTime::HiRes -e 'print(1*Time::HiRes::gettimeofday),"\n"'`
printf -v TIME "%0.3F"  $(echo "$end - $begin"|bc )

if [ -z "$RESULT" ]
then
  echo "-------------------------------------"
  echo "$INDEX subtitle(s) successfully processed in $TIME seconds."
  echo "An EDL file has been created in the same directory as the original SRT file."
  echo "Enjoy!"
  echo ""

  RESULT="$INDEX subtitle(s) successfully processed in $TIME seconds.\nAn EDL file has been created in the same directory as the original SRT file."

else
  echo "-------------------------------------"
  echo "There were build errors, please check the log file in your home directory."
  echo "$INDEX subtitle(s) successfully processed in $TIME seconds."
  echo $RESULT
  echo ""

  RESULT="$INDEX subtitle(s) successfully processed in $TIME seconds.\n$RESULT"

fi

echo -e $RESULT>>~/"XBMC Language Filter.log"
